var util = require('../../utils/util.js');
var ajax = require('../../utils/ajax.js');
var common = require('../../utils/common.js');
var PageBase = require('../../common/PageBase.js');
var app = getApp();

Page(common.extendPage(PageBase, {
  data: {
    avatar: '',
    mobile: '',
    nickname: '',
    isShow: false,
    defaultVal: '',
    madalTitle: '昵称',
    loading:true
  },
  onLoad(options) {
    this.getUser();
  },
  /**
   * 修改昵称
   */
  _editNickName(evt) {
    var {
      value
    } = evt.currentTarget.dataset;
    this.setData({
      isShow: true,
      defaultVal: value
    })
  },
  /**
   * 取消昵称修改
   */
  _cancel() {
    this.setData({
      isShow: false,
      defaultVal: ''
    })
  },
  /**
   * 提交昵称修改
   */
  _confirm() {
    var paramsUrl = '/public/api/user/profile';
    var parmasData = {
      uid: wx.getStorageSync('uid'),
      nickname: this._modalVal || this.data.nickname
    }
    ajax.P({
      url: paramsUrl,
      data: parmasData,
      success: (res,isLoadcb) => {
        this.setData({
          isShow: false,
          nickname: res.data.nickname
        })
        isLoadcb && isLoadcb();
      },
      fail: (res, isTips) => {
        if (res.message == '没有改变') {
          util.tips('新的昵称不能和之前相同');
        }
      },
      isTips:true
    })
  },
  /**
   * 获取模态输入框信息
   */
  _getModalVal(evt) {
    this._modalVal = evt.detail.value;
  },
  /**
   * 获取用户信息
   */
  getUser() {
    var parmasUrl = '/public/api/user/getUser';
    var paramsData = {
      uid: wx.getStorageSync('uid')
    };
    ajax.P({
      url: parmasUrl,
      data: paramsData,
      success: (res,isLoadcb) => {
        var res = res.data;
        this.setData({
          avatar: res.avatar,
          mobile: res.mobile,
          nickname: res.nickname,
          loading:false
        })
        isLoadcb && isLoadcb();
      },
      fail: (res) => {
      }
    })
  },
  /**
   * 修改头像
   */
  _editAvatar() {
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        // tempFilePath可以作为img标签的src属性显示图片
        const tempFilePaths = res.tempFilePaths;
        var paramsUrl = '/public/api/user/profile';
        var paramsData = {
          uid: wx.getStorageSync('uid'),
          avatar: tempFilePaths
        };
        ajax.P({
          url: paramsUrl,
          data: paramsData,
          success: (res,isLoadcb) => {
            this.setData({
              avatar: res.data.avatar
            })
            isLoadcb && isLoadcb();
          },
          fail: (res) => {
          }
        })
      }
    })
  }
}));